import json
import os
import sys

def get_target_folder():
    args = sys.argv
    # print(f"args:{args}")
    if len(args)!=2:
        raise Exception("The argument should be a path")
    return args[1]
def main():
    
    target_folder=get_target_folder()
    # print(f"target_folder:{target_folder}")
    os.chdir(target_folder)
    # target_folder="/Talon_tools/test_project/tmux/bug_reports"
    # target_folder="/Talon_tools/test_project/cJSON/bug_reports"

    # 读取所有JSON文件
    json_files = [file for file in os.listdir(target_folder) if file.endswith('.json') and file!="total_bugs.json"]
    # 创建一个字典来存储不重复的bug
    new_json=remove_dumplicate(target_folder,json_files)
    
    # 将去重后的数据保存到新的JSON文件
    with open('total_bugs.json', 'w') as file:
        json.dump(new_json, file, indent=4)
# 遍历所有bugreport,进行文件名的可视化，去重，以及合并
def remove_dumplicate(target_folder,json_files):
    targets=[]
    for json_file in json_files:
        json_path=os.path.join(target_folder,json_file)
        with open(json_path, 'r') as file:
            data = json.load(file)
        # 提取所有的bug信息
        deduplicated_data=[]
        total_bugs=0
        for BugTypes in data['BugTypes']:
            reports = BugTypes['Reports']
            unique_bugs = {}
            # 遍历每个报告
            for report in reports:
                first_step = report['DiagSteps'][0]  # 获取第一步
                last_step = report['DiagSteps'][-1]  # 获取最后一步
                key = (
                    data['SrcFiles'][first_step['File']], first_step['Line'], first_step['Tip'], first_step['FuncName'],
                    data['SrcFiles'][last_step['File']], last_step['Line'], last_step['Tip'],last_step['FuncName']
                )

                # 如果该bug的关键信息尚未在unique_bugs中出现，将其添加
                if key not in unique_bugs:
                    # 将step的File替换为文件名
                    for step in report['DiagSteps']:
                        fileName = data['SrcFiles'][step['File']]
                        #文件名替换
                        step['File'] = fileName
                    unique_bugs[key] = report
            # 创建一个包含所有不重复bug的JSON对象
            total_bugs=len(unique_bugs)+total_bugs
            deduplicated_data.append( 
                    {
                        "Name": BugTypes["Name"],
                        "Description": BugTypes["Description"],
                        "TotalReports": len(unique_bugs),
                        "Reports": list(unique_bugs.values())
                    }
            )
        
        targets.append({
                "Target": data['Target'],
                "TotalBugs": total_bugs,
                "BugTypes": deduplicated_data
            }
        )
        # 统计所有target sum 的总和
        bug_sum=0
        for target in targets:
            bug_sum+=target['TotalBugs']
        new_result=[]
        new_result.append({"BugSum":bug_sum,
                        "Targets":targets})
    return new_result
if __name__ == "__main__":
    # test()
    # exit()
    main()